package com.example.service.impl;

import com.example.domain.ResponseResult;
import com.example.domain.entity.LoginUser;
import com.example.domain.entity.User;
import com.example.domain.vo.BlogUserLoginVo;
import com.example.domain.vo.UserInfoVo;
import com.example.service.BlogLoginService;
import com.example.utils.BeanCopyUtils;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //传入的要是Authentication类型参数
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //会调用userdetailService进行用户认证，默认的是从内存中查询
        //所以要重写userdetailService实现类
        if(Objects.isNull(authentication)){
            throw new RuntimeException("用户名或密码错误");
        }

        //获取userID，生成token
        /** 静态类静态方法，所以不需要注入 */
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId=loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //存入redis
        redisCache.setCacheObject("bloglogin:"+userId,loginUser);
        //返回token和userinfo
        BlogUserLoginVo vo=new BlogUserLoginVo(jwt, BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class));
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        //删除redis的用户信息，从token中获取
        //之前从过滤器传入的authentication
        Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userId
        Long userId=loginUser.getUser().getId();
        redisCache.deleteObject("bloglogin:"+userId);

        return ResponseResult.okResult();
    }
}
